var system = require('system');
var arg_content = system.args[4];
var arg_username = system.args[5];
var arg_password = system.args[6];
var arg_threadUrl = system.args[7];
var url  = system.args[8];
url = url || 'http://www.lnsuu.com/forum.php';

var casper = require('casper').create({
        "pageSettings" : {
            loadImages: false,
            loadPlugins: false,
            javascriptEnabled: true,
            localToRemoteUrlAccessEnabled: false,
            resourceTimeout: 5000
        },
        clientScripts:[  
            'jquery.js'  
        ],
	    waitTimeout: 20000, 
        timeout: 20000,
        logLevel: "error",//日志等级
        verbose: true,    // 记录日志到控制台
        onLoadError: function(casper, url, status) {
            this.echo(url + "===>loadError " + status);
            casper.exit();
        },
        onWaitTimeout: function(timeout) {
            console.log('waitTimeout:' + timeout);
            console.log(document.title);
            casper.exit();
        },
        httpStatusHandlers: {
            404: function(self, resource) {
                self.echo(resource.url + ' not found STATUS_ERROR (404)');
                casper.exit();
            },
            500: function(self, resource) {
                self.echo(resource.url + ' gave an error STATUS_ERROR (500)');
                casper.exit();
            },
            200: function(self, resource) {
                
            }
        }
});

if(!arg_content || !arg_username || !arg_password) {
    console.log('content/username/password/threadUrl required');
    casper.exit();
}
else {
    console.log(url + ' started.');

    //login
    casper.start(url).waitForSelector('#ls_username', function(){
        var username = casper.evaluate(function(username, password) {
            document.querySelector('#ls_username').value = username;
            document.querySelector('#ls_password').value = password;
            document.querySelector('form[id="lsform"]').submit();

            return document.querySelector('#ls_username').value;

        }, arg_username, arg_password);

        console.log(username + ' logined');
    });

    casper.thenOpen(arg_threadUrl, function(){
        console.log('opening ' + arg_threadUrl);
    });

    //reply
    casper.waitForSelector('#fastpostmessage', function(){
        var selectedIndex = casper.evaluate(function(e_textarea) {
            document.querySelector('#fastpostmessage').value = e_textarea;
            document.querySelector('form[id="fastpostform"]').submit();

            return document.querySelector('#fastpostmessage').value;

        }, arg_content);

        console.log(arg_threadUrl + ' replyed ' + selectedIndex);
    });

    casper.run(function () {
        //this.echo(this.getHTML());
        casper.exit();
    });

}
